#include <QFile>
#include <QPainter>
#include <QTextCodec>
#include <QByteArray>
#include <QTime>
#include <QString>
#include "lyric.h"

extern "C" {
#include "sandcat.h"
}

Lyric::Lyric(QWidget *parent) :
    QWidget(parent)
{
    prepareSuccess = false;
    lineHeight = 15;
    align = Qt::AlignCenter;
}

Lyric::~Lyric()
{
}

void Lyric::refresh()
{
    if( STATUS_now_playing() == NULL ){
        return;
    }

    if( musicFileName != tr( ENTRY_name(STATUS_now_playing()) ) )
    {
        musicFileName = tr( ENTRY_name(STATUS_now_playing()) );
        prepareSuccess = prepare( musicFileName );
        if(prepareSuccess == false)
        {
            lyricLine.clear();
            TimeStringMap.clear();
            curTime = QTime(0,0,0,0);
            return;
        }
        else
        {
            qDebug("%s: %s", "prepareSuccess", ENTRY_name(STATUS_now_playing()) );
        }
    }

    if(prepareSuccess == false)
        return;

    long duration_msec = ENTRY_duration( STATUS_now_playing() ) / 1000;
    long cur_msec = ( (double)duration_msec / 1000 * STATUS_position() );
    curTime = QTime(0,0,0,0);
    curTime = curTime.addMSecs(cur_msec);
    //qDebug("relocation:: %s", curTime.toString(tr("mm:ss.zzz")).toUtf8().data() );

}

bool Lyric::prepare(QString musicFileName)
{
    lyricLine.clear();
    TimeStringMap.clear();

    int suffixPosition = musicFileName.lastIndexOf(QChar('.'));
    musicFileName.replace( suffixPosition, musicFileName.size() - suffixPosition, tr(".lrc") );
    this->lyricFileName = musicFileName;

    QFile file(this->lyricFileName);
    if( ! file.exists())
        return false;
    if( ! file.open(QIODevice::ReadOnly | QIODevice::Text))
        return false;

    qDebug("%s", ENTRY_name(STATUS_now_playing()) );
    qDebug("%s", this->lyricFileName.toUtf8().data() );

    while( ! file.atEnd() )
        lyricLine.append( file.readLine() );

    QList<QByteArray>::iterator i = lyricLine.begin();
    for( ; i != lyricLine.end(); i++ )
    {
        qDebug("%s", (*i).data());
        if((*i).isEmpty())
            continue;

        QString string;
        QList<QByteArray> splited = (*i).split(']');
        if(splited.size() < 2)
            continue;
        else
            string = QTextCodec::codecForName("GB18030")->toUnicode(splited.last());

        QList<QByteArray>::iterator i_splited = splited.begin();
        for( ; i_splited != splited.end() - 1; i_splited++ )
        {
            if( (*i_splited).at(1) < '0' || (*i_splited).at(1) > '9' )
                break;

            QString stime = tr(((*i_splited).remove(0, 1))+='0');
            //qDebug("%s", stime.toUtf8().data() );

            //QTime time = QTime::fromString( stime, tr("mm:ss.zzz") ); //不知道为什么不成功
            QTime time(0, stime.left(2).toInt(), stime.mid(3, 2).toInt(), stime.right(3).toInt());
            TimeStringMap.insert(time, string);
            qDebug("%s -- %s", time.toString(tr("mm:ss.zzz")).toUtf8().data(), string.toUtf8().data() );
        }

    }
    if(TimeStringMap.isEmpty())
        return false;
    else
        return true;
}

void Lyric::paintEvent ( QPaintEvent * )
{

    if( ! prepareSuccess || TimeStringMap.isEmpty() )
        return;

    QMap<QTime, QString>::iterator i = TimeStringMap.upperBound(curTime);
    if( i.key() != TimeStringMap.begin().key() )
        --i;

    int offsetTime = ( i.key() ).msecsTo(curTime);
    float scale = 0;
    if( TimeStringMap.contains( (i+1).key() ) ){
        int lineTime = (i).key().msecsTo( (i+1).key() );
        scale = (float)offsetTime / (float)lineTime;
    }

    QPainter painter(this);
    int lineNum = this->height() / lineHeight + 4;
    for( int offset = 0 ; offset < lineNum / 2 ; ++offset )
    {
        QMap<QTime, QString>::iterator ni = i - offset;
        if( TimeStringMap.contains( ni.key() ) && (ni.key() <= i.key()) && (ni != TimeStringMap.end()) )
            painter.drawText( 0, (this->height() / 2) - (offset * lineHeight) - (int)((float)lineHeight * scale),
                              this->width(), lineHeight, align,
                              ni.value() );

        QMap<QTime, QString>::iterator pi = i + offset;
        if( TimeStringMap.contains( pi.key() ) && (pi.key() >= i.key()) && (ni != TimeStringMap.end()) )
            painter.drawText( 0, (this->height() / 2) + (offset * lineHeight) - (int)((float)lineHeight * scale),
                              this->width(), lineHeight, align,
                              pi.value() );

    }


}
